const { Transform } = require('stream');

/**
 * 流内容处理
 * @param {object} file 
 * @param {function} fn 
 * @returns Buffer
 */
function contentForFile(file, fn) {
    let content = file.contents.toString()
    let result = content
    if (typeof fn == 'function') {
        result = fn(content, file)
    }
    if (typeof result == 'undefined') {
        result = content
    }
    let buf = Buffer.from(result)
    return buf
}

/**
 * 文件流中间件
 * @param {function} fn 
 * @returns Transform
 */
function pipeMiddle(fn) {
    return new Transform({
        objectMode: true,
        transform(file, encoding, callback) {
            file.contents = contentForFile(file, fn)
            return callback(null, file)
        }
    })
}

module.exports = pipeMiddle